package com.ltu.timkor6.gamesite.server;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.google.appengine.repackaged.com.google.common.util.Base64;



public final class Encrypter
{
	private static Encrypter instance;

	private Encrypter()
	{
	}
	
	/**
	 * Encrypt method.
	 * @param password
	 * @return
	 */
	public synchronized String encrypt(String password)
	{
		MessageDigest md = null;
		
		// Get an instance of a message digest.
		try
		{
			md = MessageDigest.getInstance("SHA");
		}
		catch(NoSuchAlgorithmException e)
		{
			// Should never happen.
			return null;
		}
		
		// Generate the message digest.
		try
		{
			md.update(password.getBytes("UTF-8"));
		}
		catch(UnsupportedEncodingException e)
		{
			// Should never happen.
			return null;
		}
		
		// Create a string representation 
		byte raw[] = md.digest();
		
		return Base64.encode(raw);
	}
	
	/**
	 * Get the static instance, if it does not exist, then create it.
	 * @return
	 */
	public static synchronized Encrypter getInstance()
	{
		if(instance == null)
		{
			 instance = new Encrypter(); 
		} 
		
		return instance;
	}
}
